package com.work.demo.filter;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import org.apache.catalina.connector.CoyoteInputStream;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class RequestWrapperTest extends HttpServletRequestWrapper {

    private HttpServletRequest originalRequest;

    private String modifyReqBody;

    private String modifyContentType;

    public RequestWrapperTest(HttpServletRequest request, HttpServletRequest originalRequest, String modifyReqBody, String modifyContentType) {
        super(request);
        this.originalRequest = originalRequest;
        this.modifyReqBody = modifyReqBody;
        this.modifyContentType = modifyContentType;
    }

    @Override
    @SneakyThrows
    public ServletInputStream getInputStream() {
        return new ServletInputStream() {
            //获取修改后的请求体的输入流
            private final InputStream in = new ByteArrayInputStream(modifyReqBody.getBytes(originalRequest.getCharacterEncoding()));

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            @SneakyThrows
            public int read() {
                return in.read();
            }
        };
    }

    @Override
    @SneakyThrows
    public int getContentLength() {
        return modifyReqBody.getBytes(originalRequest.getCharacterEncoding()).length;
    }

    @Override
    @SneakyThrows
    public long getContentLengthLong() {
        return modifyReqBody.getBytes(originalRequest.getCharacterEncoding()).length;
    }

    @Override
    public String getContentType() {
        return StrUtil.isBlank(modifyContentType) ? originalRequest.getContentType() : modifyContentType;
    }
}
